﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using System.Collections;
using WaveMaster.Holidays.Club.Service;
using System.Configuration;
using System.Net;
using System.Net.NetworkInformation;
using System.IO;

namespace WaveMaster.Holidays.Club.ServiceClient
{
    public partial class PrinterMonitoringForm : Form
    {
        private ReportRequestService m_ReportRequestService;
        bool m_close = false;
        bool m_connect = true;
        private const string DEFAULT_PRINTER_NAME = "LOCAL";

        public PrinterMonitoringForm()
        {
            InitializeComponent();
            m_ReportRequestService = new ReportRequestService();
            textBoxMACAddress.Text = GetMacAddress();
            string url = ConfigurationManager.AppSettings["URLServer"];
            int refreshrate = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshRate"]);
            textBoxServerSOAP.Text = url;

            timerMonitoring.Interval = refreshrate;
            timerMonitoring.Tick += new EventHandler(timerMonitoring_Tick);
            timerMonitoring.Start();
            m_connect = true;
        }

        static string GetMacAddress()
        {
            string macAddresses = "";
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                // Only consider Ethernet network interfaces, thereby ignoring any
                // loopback devices etc.
                if (nic.NetworkInterfaceType != NetworkInterfaceType.Ethernet) continue;
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddresses += nic.GetPhysicalAddress().ToString();
                    break;
                }
            }
            return macAddresses;
        }

        void timerMonitoring_Tick(object sender, EventArgs e)
        {
            try
            {
                labelStatus.Visible = !labelStatus.Visible;
                labelError.Text = "";
                string url = textBoxServerSOAP.Text;
                m_ReportRequestService = Activator.GetObject(typeof(ReportRequestService), url) as ReportRequestService;

                IList reportBPdatas = m_ReportRequestService.GetBoardingPassRequestReportByMACAddress(textBoxMACAddress.Text);
                string reportSourceBP = ConfigurationManager.AppSettings["BoardingPassReportFile"];
                foreach (DataSet bp in reportBPdatas)
                {
                    ReportDocument rpdoc = new ReportDocument();
                    rpdoc.Load(reportSourceBP);
                    rpdoc.SetDataSource(bp);
                    System.Drawing.Printing.PrinterSettings printersettings = new System.Drawing.Printing.PrinterSettings();
                    printersettings.PrinterName = bp.Tables[0].Columns[bp.Tables[0].Columns.Count - 1].ColumnName; 
                    printersettings.Copies = 1;
                    printersettings.Collate = false;
                    printersettings.FromPage = 1;
                    printersettings.ToPage = 1;
                    printersettings.MaximumPage = 1;
                    rpdoc.PrintToPrinter(printersettings, new System.Drawing.Printing.PageSettings(), false);
                }

                IList reportBPtwowaydatas = m_ReportRequestService.GetBoardingPassRequestTwoWayReportByMACAddress(textBoxMACAddress.Text);
                string reportSourceBPtwoWay = ConfigurationManager.AppSettings["BoardingPassReportTwoWayFile"];
                foreach (DataSet bp in reportBPtwowaydatas)
                {
                    ReportDocument rpdoc = new ReportDocument();
                    rpdoc.Load(reportSourceBPtwoWay);
                    rpdoc.SetDataSource(bp);
                    System.Drawing.Printing.PrinterSettings printersettings = new System.Drawing.Printing.PrinterSettings();
                    printersettings.PrinterName = bp.Tables[0].Columns[bp.Tables[0].Columns.Count - 1].ColumnName;
                    printersettings.Copies = 1;
                    printersettings.Collate = false;
                    printersettings.FromPage = 1;
                    printersettings.ToPage = 1;
                    printersettings.MaximumPage = 1;
                    rpdoc.PrintToPrinter(printersettings, new System.Drawing.Printing.PageSettings(), false);
                }

                IList reportWCdatas = m_ReportRequestService.GetWhiteCardRequestReportByMACAddress(textBoxMACAddress.Text);
                string reportSourceWC = ConfigurationManager.AppSettings["WhiteCardReportFile"];
                foreach (DataSet wc in reportWCdatas)
                {
                    ReportDocument rpdoc = new ReportDocument();
                    rpdoc.Load(reportSourceWC);
                    rpdoc.SetDataSource(wc);
                    System.Drawing.Printing.PrinterSettings printersettings = new System.Drawing.Printing.PrinterSettings();
                    printersettings.PrinterName = wc.Tables[0].Columns[wc.Tables[0].Columns.Count - 1].ColumnName;
                    printersettings.Copies = 1;
                    printersettings.Collate = false;
                    printersettings.FromPage = 1;
                    printersettings.ToPage = 1;
                    printersettings.MaximumPage = 1;
                    rpdoc.PrintToPrinter(printersettings, new System.Drawing.Printing.PageSettings(), false);
                }

                IList reportKIMSdatas = m_ReportRequestService.GetKIMSCardRequestReportByMACAddress(textBoxMACAddress.Text);
                string reportSourceKIMS = ConfigurationManager.AppSettings["KIMSCardReportFile"];
                foreach (DataSet wc in reportKIMSdatas)
                {
                    ReportDocument rpdoc = new ReportDocument();
                    rpdoc.Load(reportSourceKIMS);
                    rpdoc.SetDataSource(wc);
                    System.Drawing.Printing.PrinterSettings printersettings = new System.Drawing.Printing.PrinterSettings();
                    printersettings.PrinterName = wc.Tables[0].Columns[wc.Tables[0].Columns.Count - 1].ColumnName;
                    printersettings.Copies = 1;
                    printersettings.Collate = false;
                    printersettings.FromPage = 1;
                    printersettings.ToPage = 1;
                    printersettings.MaximumPage = 1;
                    rpdoc.PrintToPrinter(printersettings, new System.Drawing.Printing.PageSettings(), false);
                }

                notifyIcon1.Text = "WaveMaster Print Request Monitor is running";
            }
            catch (Exception x)
            {
                labelError.Text = x.Message+". Attempt to reconnect in 10 seconds.";
                buttonStart_Click(null, null);
                timerAutoConnect.Start();
                notifyIcon1.BalloonTipText = x.Message;
                notifyIcon1.ShowBalloonTip(100);
                //MessageBox.Show(x.Message);
                createErrorLog(x);
            }
        }

        private void createErrorLog(Exception x)
        {
            try
            {
                string errorLog = Application.StartupPath + @"\ErrorLog.txt";
                if (File.Exists(errorLog))
                {
                    File.Delete(errorLog);
                }
                string error = x.Message;
                while (x != null)
                {
                    error += x.Message;
                    x = x.InnerException;
                }
                StreamWriter SW = File.CreateText(errorLog);
                SW.WriteLine(DateTime.Now.ToString() + " : " + error);
                SW.Close();
            }
            catch { }
        }

        private void PrinterMonitoringForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !m_close;
            HideTonotify();
        }

        private void HideTonotify()
        {
            this.Hide();
            notifyIcon1.BalloonTipText = "WaveMaster Print Request Monitor is running";
            notifyIcon1.ShowBalloonTip(100);
            notifyIcon1.Text = notifyIcon1.BalloonTipText;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            m_close = true;
            this.Close();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (buttonStart.Text == "Stop")
            {
                timerMonitoring.Stop();
                buttonStart.Text = "Start";
                labelStatus.Text = "Monitoring is stop...";
                labelStatus.Visible = true;
                m_connect = false;
            }
            else
            {
                timerMonitoring.Start();
                buttonStart.Text = "Stop";
                labelStatus.Text = "Monitoring is running...";
                m_connect = true;
            }
        }

        private void PrinterMonitoringForm_Load(object sender, EventArgs e)
        {
            
        }

        private void PrinterMonitoringForm_Shown(object sender, EventArgs e)
        {
            HideTonotify();
        }

        private void buttonMinimize_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timerAutoConnect_Tick(object sender, EventArgs e)
        {
            buttonStart_Click(sender, e);
            labelError.Text = "";
            timerAutoConnect.Stop();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_close = true;
            this.Close();
        }
    }
}
